package com.example.multi.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.example.multi.entity.DataResp;
import com.example.multi.entity.Resp;
import com.example.multi.entity.User;
import com.example.multi.service.ITestAsyncService;
import com.example.multi.service.ITestRequestService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Slf4j
@RestController
@RequestMapping(value = "/v1/async")
public class TestAsyncController {

    @Autowired
    ITestAsyncService testAsyncService;

    @ApiOperation(value = "调用接口")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Resp<Integer> test() throws ExecutionException, InterruptedException {
        log.info("asyncFunction_1 start");
        testAsyncService.asyncFunction_1();
        log.info("asyncFunction_1 start");

        log.info("asyncFunction_2 start");
        testAsyncService.asyncFunction_2();
        log.info("asyncFunction_2 end");

        log.info("asyncFunction_3 start");
        testAsyncService.asyncFunction_3();
        log.info("asyncFunction_3 end");


        log.info("asyncReturnDta_1 & asyncReturnDta_2 start");
        Future<Integer> future = testAsyncService.asyncReturnDta_1();
        testAsyncService.asyncReturnDta_2();
        log.info("asyncReturnDta_1 & asyncReturnDta_2 end");

        Integer resp = future.get();
        log.info("future.get() resp:{}",resp);
        return Resp.buildDataSuccess(resp);
    }

    @ApiOperation(value = "调用接口-超时")
    @RequestMapping(value = "/async_timeOut", method = RequestMethod.GET)
    public Resp<Integer> async_timeOut() throws ExecutionException, InterruptedException {
        TimeInterval timeInterval = DateUtil.timer();
        log.info("asyncReturnDtaTimeOut start");
        Future<Integer> future = testAsyncService.asyncReturnDtaTimeOut();
        log.info("asyncReturnDtaTimeOut end");

        Integer resp = null;
        try {
            //一秒内 返回不了数据就报错
            resp = future.get(1, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            resp = -1;//请求超时了，相当于熔断，服务降级
            log.error("asyncReturnDtaTimeOut future.get(1, TimeUnit.SECONDS) timeout:",e);
        }

        log.info("future.get() resp:{}  耗时：{}毫秒",resp,timeInterval.intervalRestart());
        return Resp.buildDataSuccess(resp);
    }

}
